"""
    client_socket     创建套接字，建立连接
    client_view       交互
    client_collector  调用方法
"""
import sys
from socket import *
import time

HOST = '176.233.33.11'
PORT = 1944
ADDR = (HOST, PORT)
PATH_DOWN_TO = '/home/tarena/downn'


class ClientSocket:
    """
        启动客户端，建立连接
    """

    def __init__(self):
        self.socket = socket()
        self.socket.connect(ADDR)

    def run(self):
        view = ClientView(self.socket)
        view.index()


class ClientView(object):
    """
        进入客户端操作界面
    """

    def __init__(self, tcp_socket):
        self.socket = tcp_socket
        self.collector = ClientCollector(self.socket)

    def index(self):
        while True:
            print("==========================正方文件存储系统==========================")
            print("====                     输入1查看文件列表                      ====")
            print("====                     输入2进行文件下载                      ====")
            print("====                     输入3进行文件上传                      ====")
            print("====                     输入4退出文件系统                      ====")
            print("==========================正方文件存储系统==========================")
            message = input('>:')
            self.jump(message)

    def jump(self, message):
        if message == '1':
            self.look_dir()
        elif message == '2':
            self.download()
        elif message == '3':
            self.upload()
        if message == '4':
            self.exit()
            print('系统退出中.........')
            print('已退出，欢迎下次光临，88')
            sys.exit()

    def look_dir(self):
        print(self.collector.look_dir())

    def exit(self):
        self.socket.send(b'EXIT exit')

    def download(self):
        if self.collector.download():
            print('文件下载成功')
        else:
            print('文件不存在')

    def upload(self):
        evidence = self.collector.up_load()
        if evidence == 0:
            print('文件上传成功')
        elif evidence == 1:
            print('文件在服务器已存在，请重新选择上传文件')
        else :
            print('文件不存在，请重新选择上传文件')


class ClientCollector():
    """
        发送客户端请求
    """

    def __init__(self, tcp_socket):
        self.socket = tcp_socket

    def look_dir(self):
        print("已发送请求")
        """向服务器发送查看请求"""
        request = 'LIST look'.encode()
        self.socket.send(request)
        print('等待接收文件')
        evidence = self.socket.recv(1024)
        if evidence == b'OK':
            file = self.socket.recv(1024).decode()
            return file
        else:
            return '文件列表为空'

    def download(self):
        file_list = self.look_dir()
        request = 'RETR'.encode()
        self.socket.send(request)
        print('请选择你要下载的文件')
        print(file_list)
        filename = input('请输入对应文件名下载文件')
        self.socket.send(filename.encode())
        response = self.socket.recv(1024).decode()
        if response == 'OK':
            file_path = input('请输入文件存储位置') + '/' + filename
            f = open(file_path, 'wb')
            while True:
                text = self.socket.recv(1024)
                print('文件接收中')
                if text == b'##':
                    break
                f.write(text)
            f.close()
            return True
        else:
            return False

    def up_load(self):
        request = 'STOR'.encode()  # 告诉服务器要上传文件了
        self.socket.send(request)
        print('验证通过开始上传流程')
        try:
            filepath = input('请输入文件（格式为路径+文件名）：').encode()
            with open(filepath) as f: # 判断输入的文件是否存在，存在向客户端发送文件路径
                self.socket.send(filepath)
                print('已向服务器发送文件路径')
                response = self.socket.recv(1024).decode()
                print('已获取服务器验证结果')
                if response == 'OK':  # 客户端验证完文件名不存在
                    print('验证成功，开始发送文件给服务器')
                    while True:
                        text = f.read(1024)
                        if not text:
                            break
                        self.socket.send(text.encode())
                    time.sleep(0.5)
                    self.socket.send(b'##')
                    print('发送完毕')
                    return 0
                else:
                    return 1
        except:
            # 文件不存在返回False
            return False


if __name__ == '__main__':
    client = ClientSocket()
    client.run()
